package com.ouyunc.oauth2.exception.handler;

import com.ouyunc.common.constant.Auth2Constant;
import com.ouyunc.common.constant.enums.ResponseCodeEnum;
import com.ouyunc.common.base.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 自定义过滤器filter 中的异常捕获,重写了web 模块中的filter 处理器
 */
@RestController
public class Auth2GlobalFilterExceptionHandler extends BasicErrorController {
    Logger log = LoggerFactory.getLogger(Auth2GlobalFilterExceptionHandler.class);

    public Auth2GlobalFilterExceptionHandler() {
        this(new DefaultErrorAttributes(), new ErrorProperties());
    }

    public Auth2GlobalFilterExceptionHandler(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    @Override
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        // 处理client_id 确实抛出同一的异常信息
        if (request instanceof SecurityContextHolderAwareRequestWrapper && StringUtils.isBlank(request.getParameter(Auth2Constant.CLIENT_ID))) {
            return new ResponseEntity(ResponseResult.fail(ResponseCodeEnum.BAD_REQUEST, "缺少参数：client_id！"), getStatus(request));
        }
        Map<String, Object> errorAttributes = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.STACK_TRACE));
        HttpStatus status = getStatus(request);
        String message = errorAttributes.get("message").toString();
        if (StringUtils.isBlank(message)) {
            message = errorAttributes.get("error").toString();
        }
        log.error("oauth2 异常了: {}", message);
        return new ResponseEntity(ResponseResult.common(status.value(), message, null,false), status);
    }
}
